package com.example.javaproject.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javaproject.common.R;
import com.example.javaproject.entity.Teacher;
import com.example.javaproject.entity.WorkTimeRecord;
import com.example.javaproject.entity.Position;
import com.example.javaproject.entity.PositionApplication;
import com.example.javaproject.entity.Salary;
import com.example.javaproject.entity.User;
import com.example.javaproject.service.TeacherService;
import com.example.javaproject.service.WorkTimeRecordService;
import com.example.javaproject.service.PositionService;
import com.example.javaproject.service.PositionApplicationService;
import com.example.javaproject.service.SalaryService;
import com.example.javaproject.service.UserService;
import com.example.javaproject.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

//da
@RestController
@RequestMapping("/api/teacher")
public class TeacherController {
    
    @Autowired
    private TeacherService teacherService;
    
    @Autowired
    private WorkTimeRecordService workTimeRecordService;
    
    @Autowired
    private PositionService positionService;
    
    @Autowired
    private PositionApplicationService positionApplicationService;
    
    @Autowired
    private SalaryService salaryService;

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public R getAllTeachers() {
        List<Teacher> teachers = teacherService.lambdaQuery()
            .eq(Teacher::getIsDeleted, 0)
            .orderByAsc(Teacher::getId)
            .list();
        return R.ok(teachers);
    }

    /**
     * 获取教师需要审核的工时记录
     */
    @GetMapping("/work-time-review")
    public R getWorkTimeRecordsForReview(
            @RequestHeader("Authorization") String authHeader,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "8") int pageSize) {
        
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }
        
        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }
        
        // 根据用户ID查询教师ID
        Teacher teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("未找到教师信息");
        }
        Integer teacherId = teacher.getId();
        
        // 分页查询该教师需要审核的工时记录（未审核状态）
        Page<WorkTimeRecord> page = new Page<>(pageNum, pageSize);
        IPage<WorkTimeRecord> recordPage = workTimeRecordService.lambdaQuery()
                .eq(WorkTimeRecord::getTeacherId, teacherId)
                .eq(WorkTimeRecord::getStatus, 0) // 0: 未审核
                .eq(WorkTimeRecord::getIsDeleted, false)
                .orderByDesc(WorkTimeRecord::getCreateTime)
                .page(page);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (WorkTimeRecord record : recordPage.getRecords()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", record.getId());
            map.put("date", record.getDate());
            map.put("startTime", record.getStartTime());
            map.put("endTime", record.getEndTime());
            map.put("description", record.getDescription());
            map.put("proofUrl", record.getProofUrl());
            map.put("status", record.getStatus());
            
            // 根据岗位ID获取岗位名称
            Position position = positionService.getById(record.getPositionId());
            map.put("positionName", position != null ? position.getName() : "-");
            
            result.add(map);
        }
        
        Map<String, Object> pageData = new HashMap<>();
        pageData.put("records", result);
        pageData.put("total", recordPage.getTotal());
        
        return R.ok(pageData);
    }

    /**
     * 审核工时记录（通过或拒绝）
     */
    @PutMapping("/work-time-review/{recordId}")
    public R reviewWorkTimeRecord(
            @RequestHeader("Authorization") String authHeader,
            @PathVariable Integer recordId,
            @RequestParam Integer status) { // 1: 通过, 2: 拒绝
        
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }
        
        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }
        
        // 根据用户ID查询教师ID
        Teacher teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("未找到教师信息");
        }
        Integer teacherId = teacher.getId();
        
        // 查询工时记录
        WorkTimeRecord record = workTimeRecordService.getById(recordId);
        if (record == null) {
            return R.error("工时记录不存在");
        }
        
        // 验证该记录是否属于当前教师
        if (!record.getTeacherId().equals(teacherId)) {
            return R.error("无权审核此工时记录");
        }
        
        // 验证记录状态是否为未审核
        if (record.getStatus() != 0) {
            return R.error("该记录已被审核");
        }
        
        // 更新状态
        record.setStatus(status);
        record.setUpdateTime(java.time.LocalDateTime.now());
        
        boolean success = workTimeRecordService.updateById(record);
        if (success) {
            // 如果审核通过，创建工资记录
            if (status == 1) {
                try {
                    createSalaryRecord(record);
                } catch (Exception e) {
                    // 工资记录创建失败不影响审核结果，但记录错误
                    System.err.println("创建工资记录失败: " + e.getMessage());
                }
            }
            
            String action = status == 1 ? "通过" : "拒绝";
            return R.ok(action + "成功");
        } else {
            return R.error("审核失败");
        }
    }
    
    /**
     * 创建或更新工资记录
     */
    private void createSalaryRecord(WorkTimeRecord record) {
        // 1. 获取岗位信息
        Position position = positionService.getById(record.getPositionId());
        if (position == null) {
            throw new RuntimeException("岗位不存在");
        }
        
        // 2. 计算本次工时（小时）
        double currentHours = 0.0;
        if (record.getStartTime() != null && record.getEndTime() != null) {
            LocalTime startTime = record.getStartTime().toLocalTime();
            LocalTime endTime = record.getEndTime().toLocalTime();
            Duration duration = Duration.between(startTime, endTime);
            currentHours = duration.toMinutes() / 60.0; // 转换为小时
            
            // 确保工时不为负数
            if (currentHours < 0) {
                throw new RuntimeException("工时计算错误：结束时间不能早于开始时间");
            }
        }
        
        // 3. 计算本次工资
        BigDecimal hourlyRate = new BigDecimal(position.getSalary());
        BigDecimal currentSalary = hourlyRate.multiply(new BigDecimal(currentHours));
        
        // 4. 查询是否已存在相同的工资记录（学生ID、岗位ID、教师ID都相同）
        Salary existingSalary = salaryService.lambdaQuery()
                .eq(Salary::getStudentId, record.getStudentId())
                .eq(Salary::getPositionId, record.getPositionId())
                .eq(Salary::getTeacherId, record.getTeacherId())
                .eq(Salary::getIsDeleted, false)
                .one();
        
        if (existingSalary != null) {
            // 5. 如果存在，更新总工时和总工资
            int currentHoursInt = (int) Math.round(currentHours);
            int newTotalHours = existingSalary.getTotalHour() + currentHoursInt;
            
            // 检查TINYINT限制（-128到127）
            if (newTotalHours > 127) {
                throw new RuntimeException("总工时超过限制（最大127小时）");
            }
            if (newTotalHours < 0) {
                throw new RuntimeException("总工时不能为负数");
            }
            
            BigDecimal newTotalSalary = existingSalary.getTotalSalary().add(currentSalary);
            
            existingSalary.setTotalHour(newTotalHours);
            existingSalary.setTotalSalary(newTotalSalary);
            existingSalary.setUpdateTime(java.time.LocalDateTime.now());
            
            boolean updateSuccess = salaryService.updateById(existingSalary);
            if (!updateSuccess) {
                throw new RuntimeException("工资记录更新失败");
            }
        } else {
            // 6. 如果不存在，创建新的工资记录
            int currentHoursInt = (int) Math.round(currentHours);
            
            // 检查TINYINT限制
            if (currentHoursInt > 127) {
                throw new RuntimeException("单次工时超过限制（最大127小时）");
            }
            if (currentHoursInt < 0) {
                throw new RuntimeException("工时不能为负数");
            }
            
            Salary salary = new Salary();
            salary.setTotalHour(currentHoursInt);
            salary.setTotalSalary(currentSalary);
            salary.setStatus(0); // 0: 未审核
            salary.setIsDeleted(0);
            salary.setCreateTime(java.time.LocalDateTime.now());
            salary.setUpdateTime(java.time.LocalDateTime.now());
            salary.setStudentId(record.getStudentId());
            salary.setTeacherId(record.getTeacherId());
            salary.setPositionId(record.getPositionId());
            
            boolean saveSuccess = salaryService.save(salary);
            if (!saveSuccess) {
                throw new RuntimeException("工资记录保存失败");
            }
        }
    }

    /**
     * 测试工资记录逻辑
     */
    @GetMapping("/test-salary-logic")
    public R testSalaryLogic(
            @RequestHeader("Authorization") String authHeader,
            @RequestParam Integer studentId,
            @RequestParam Integer positionId) {
        
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }
        
        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }
        
        // 根据用户ID查询教师ID
        Teacher teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("未找到教师信息");
        }
        Integer teacherId = teacher.getId();
        
        // 查询是否已存在相同的工资记录
        Salary existingSalary = salaryService.lambdaQuery()
                .eq(Salary::getStudentId, studentId)
                .eq(Salary::getPositionId, positionId)
                .eq(Salary::getTeacherId, teacherId)
                .eq(Salary::getIsDeleted, false)
                .one();
        
        Map<String, Object> result = new HashMap<>();
        result.put("exists", existingSalary != null);
        if (existingSalary != null) {
            result.put("totalHour", existingSalary.getTotalHour());
            result.put("totalSalary", existingSalary.getTotalSalary());
            result.put("status", existingSalary.getStatus());
        }
        
        return R.ok(result);
    }

    @GetMapping("/dashboard-stats")
    public R getDashboardStats(@RequestHeader("Authorization") String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }
        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }
        
        // 1. 通过userId查teacherId
        Teacher teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("未找到教师信息");
        }
        Integer teacherId = teacher.getId();
        
        // 2. 获取活跃岗位数量（该教师的岗位，status=0表示招聘中）
        long activePositions = positionService.lambdaQuery()
                .eq(Position::getTeacherId, teacherId)
                .eq(Position::getStatus, 0)
                .eq(Position::getIsDeleted, 0)
                .count();
        
        // 3. 获取待审批申请数量（该教师岗位的申请，status=0表示待审核）
        long pendingApplications = positionApplicationService.lambdaQuery()
                .inSql(PositionApplication::getPositionId, 
                    "SELECT id FROM position WHERE teacher_id = " + teacherId + " AND is_deleted = 0")
                .eq(PositionApplication::getStatus, 0)
                .eq(PositionApplication::getIsDeleted, 0)
                .count();
        
        // 4. 获取在岗学生数量（该教师岗位的已通过申请）
        long activeStudents = positionApplicationService.lambdaQuery()
                .inSql(PositionApplication::getPositionId, 
                    "SELECT id FROM position WHERE teacher_id = " + teacherId + " AND is_deleted = 0")
                .eq(PositionApplication::getStatus, 1) // 1表示已通过
                .eq(PositionApplication::getIsDeleted, 0)
                .count();
        
        // 5. 获取本月工时（该教师岗位的本月工时记录，只统计已审核通过的）
        java.time.LocalDateTime now = java.time.LocalDateTime.now();
        java.time.LocalDateTime startOfMonth = now.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        java.time.LocalDateTime endOfMonth = now.withDayOfMonth(now.toLocalDate().lengthOfMonth()).withHour(23).withMinute(59).withSecond(59).withNano(999999999);
        
        List<WorkTimeRecord> monthRecords = workTimeRecordService.lambdaQuery()
                .inSql(WorkTimeRecord::getPositionId, 
                    "SELECT id FROM position WHERE teacher_id = " + teacherId + " AND is_deleted = 0")
                .eq(WorkTimeRecord::getIsDeleted, 0)
                .eq(WorkTimeRecord::getStatus, 1) // 只统计已审核通过的记录
                .ge(WorkTimeRecord::getCreateTime, startOfMonth)
                .le(WorkTimeRecord::getCreateTime, endOfMonth)
                .list();
        
        double totalWorkHours = 0.0;
        for (WorkTimeRecord record : monthRecords) {
            if (record.getStartTime() != null && record.getEndTime() != null) {
                try {
                    java.time.LocalTime start = record.getStartTime().toLocalTime();
                    java.time.LocalTime end = record.getEndTime().toLocalTime();
                    java.time.Duration duration = java.time.Duration.between(start, end);
                    totalWorkHours += duration.toMinutes() / 60.0;
                } catch (Exception ignore) {}
            }
        }
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("activePositions", activePositions);
        stats.put("pendingApplications", pendingApplications);
        stats.put("activeStudents", activeStudents);
        stats.put("totalHours", Math.round(totalWorkHours * 10.0) / 10.0); // 保留一位小数
        
        return R.ok(stats);
    }

    @GetMapping("/info")
    public R getTeacherInfo(@RequestHeader("Authorization") String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }
        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }

        // 获取老师信息
        Teacher teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("未找到老师信息");
        }

        // 获取用户信息
        User user = userService.getById(userId);
        if (user == null) {
            return R.error("未找到用户信息");
        }

        // 组装返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("name", teacher.getName());
        data.put("teacherId", teacher.getId());
        data.put("college", teacher.getCollege());
        data.put("username", user.getUsername());
        data.put("mail", user.getMail());
        data.put("phone", user.getPhone());
        data.put("password", user.getPassword());

        return R.ok(data);
    }

    @PutMapping("/info")
    public R updateTeacherInfo(@RequestHeader("Authorization") String authHeader, @RequestBody Map<String, String> data) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }
        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }

        // 获取老师信息
        Teacher teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("未找到老师信息");
        }

        // 获取用户信息
        User user = userService.getById(userId);
        if (user == null) {
            return R.error("未找到用户信息");
        }

        // 更新用户信息
        if (data.containsKey("username")) {
            user.setUsername(data.get("username"));
        }
        if (data.containsKey("password") && !data.get("password").isEmpty()) {
            user.setPassword(data.get("password")); // 注意：实际应用中需要加密
        }
        if (data.containsKey("mail")) {
            user.setMail(data.get("mail"));
        }
        if (data.containsKey("phone")) {
            user.setPhone(data.get("phone"));
        }

        // 保存更新
        boolean success = userService.updateById(user);
        if (!success) {
            return R.error("更新失败");
        }

        return R.ok("更新成功");
    }
} 